﻿using System;
using System.IO;
using Microsoft.SharePoint.Administration;

namespace EnhancedSolutions
{
    class ExtractedSolution : IDisposable
    {
        private SPSolution solution;
        private string targetPath;

        /// <summary>
        /// Initializes a new instance of the <see cref="ExtractedSolution"/> class.
        /// </summary>
        /// <param name="solutionName">Name of the solution.</param>
        public ExtractedSolution(string solutionName)
        {
            this.solution = SPFarm.Local.Solutions[solutionName];
            this.targetPath = Helper.GetTemporaryPath(this.Name);
        }

        /// <summary>
        /// Extracts the file to the temporary folder.
        /// </summary>
        public void Extract()
        {
            this.solution.SolutionFile.SaveAs(this.targetPath);
        }

        /// <summary>
        /// Gets the targetpath.
        /// </summary>
        public string Targetpath
        {
            get
            {
                return this.targetPath;
            }
        }

        /// <summary>
        /// Gets the solution.
        /// </summary>
        public SPSolution Solution
        {
            get
            {
                return this.solution;
            }
        }

        /// <summary>
        /// Gets the name.
        /// </summary>
        public string Name
        {
            get
            {
                return this.solution.Name;
            }
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            File.Delete(this.targetPath);
            this.solution = null;
            this.targetPath = null;
        }
    }
}
